from rest_framework.status import HTTP_201_CREATED, HTTP_302_FOUND
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings

from fdfs_client.client import Fdfs_client
from tenth_power.utils.fastdfs.fastdfs_storage import FastDFSStorage


class UserTXView(APIView):

    def post(self, request):
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        result = client.upload_by_buffer(request.FILES.get('img').read())
        if result.get('Status') != 'Upload successed.':
            raise Exception('上传文件到FDFS系统失败')
        url = result.get('Remote file_id')
        url = settings.FDFS_URL + url
        return Response(
            {
                'imgurl': url
            },
            status=HTTP_201_CREATED)


class UploadCommonView(APIView):
    def post(self, request):
        fast = FastDFSStorage()
        url = fast.save(name=None, content=request.FILES.get('upload'))
        headers = {
            'Location': 'http://127.0.0.1:8080/upload_success.html?image_url=' + settings.FDFS_URL + url + '&message=true&CKEditorFuncNum=' + self.request.query_params.get(
                'CKEditorFuncNum')}
        return Response(
            status=HTTP_302_FOUND, headers=headers)
